<?php
namespace Admin\Controller;
use Think\Controller;
use Org\Util\String;
use Com\WechatAuth;

/**
 * 处理问卷相关请求
 */
class QuestionnaireController extends BaseController
{
	private $wechat;
	protected function _initialize()
	{
		parent::_initialize();
		$this->getsetting();
	}

    /* 问卷列表 */
    public function index()
    {
    	$data = M('Questionnaires')->where("iswp=1")->alias('q')->join('left join wpsk_company c on q.type=c.id')->field('q.ispub as ispub,q.id as id,c.name as type,q.name as name,q.description as description ,q.create_date as create_date,q.expire_date as expire_date,q.qrcode as qrcode')->select();
        $this->assign('questionnaires',$data);
		
      $this->display();
    }

    /* 问卷添加 */
    public function add()
    {
        if( IS_POST ){ //访问页面
      
            $questionnaires = M('Questionnaires');
         	if ($_FILES ['pic'] ['name'] != null)
         		$data ["pic"] = $this->upload ( $_FILES ['pic'] );
				$data ["type"] = I("post.type");
				$data ["ispub"] = I("post.ispub");
				$data ["name"] = I("post.name");
				$data['nickname']=$_SESSION["nickname"];
				$data['openid']=111;
				$data ["description"] =I("post.description"); 
				$data ["create_date"] = date("Y-m-d",time()); 
				$data ["expire_date"] = I("post.expire_date");;
                $state = $questionnaires->add($data);

                if( $state===false ){
                    $this->error('问卷添加失败，错误信息：'.$questionnaires->getDbError());
                }else{
                	$wechat=new WechatAuth(C('settings.weixin_AppID'),C('settings.weixin_AppSecret'),C('settings.weixin_Token'));
                	$temp=$wechat->qrcodeCreate($state,0);
                	 $data['qrcode'] = $temp['ticket'];
                	$questionnaires->where('id='.$state)->save($data);
                   $this->success('问卷添加成功', U('questionnaire/index'), 0);
                }
           
        }
        else{
        	$data=M('company')->select();
        	$this->assign("info",$data);
            $this->display();
        }
    }
    
 /**
     * 设置信息
     */
    private function getsetting(){
    	$settings = F('settings') ? F('settings') : M('Settings')->getField('name,value');
		C('settings', $settings);
    }

    /* 问卷编辑 */
    public function edit()
    {

        if( IS_GET ){ //访问页面
            $questionnaires = M('Questionnaires')->where("id='".I('get.id')."' and iswp=1")->field(true)->find();
            $data=M('company')->select();
        	$this->assign("info",$data);
            $this->assign($questionnaires);
            $this->display();
        }else{ //表单提交
        	   $questionnaires = M('Questionnaires');
        	   
        	
        	$ordata=$questionnaires->where("id=".I("post.id"))->find();
        	
       	 if($ordata['openid']=="111"){
      		
      		$data['nickname']=$_SESSION["nickname"];
      		}
        		if ($_FILES ['pic'] ['name'] != null)
         		$data ["pic"] = $this->upload ( $_FILES ['pic'] );
				$data ["type"] = I("post.type");
				$data ["name"] = I("post.name");
				$data ["ispub"] = I("post.ispub");
				$data ["description"] =I("post.description"); 
				$data ["create_date"] = date("Y-m-d",time()); 
				$data ["expire_date"] = I("post.expire_date");;
               
                $state = $questionnaires->where("id=".I("post.id"))->save($data);

                if( $state===false ){
                    $this->error('问卷更新失败，错误信息：'.$questionnaires->getDbError());
                }else{
                    $this->success('问卷编辑成功', '/admin/questionnaire/index', 0);
                }
          
        }
    }

    /* 问卷删除 */
    public function delete()
    {
        if( is_array(I('id')) ){ //批量删除
            $id = implode( ',', I('id', array(), 'intval') );
        }else{ //单个删除
            $id = I('id/d');
        }

        $questionnaires = D('Questionnaires');
        $state = $questionnaires->relation('Questions')->delete($id);

        if( $state===false ){
            $this->error('问卷删除失败，错误信息: '.$questionnaires->getDbError()); //删除问卷，并关联删除旗下问题
        }else{
            $this->redirect('/admin/questionnaire/index');
        }
    }
    
/**
	 * 上传
	 * @param unknown_type $filename
	 * @return string
	 */
	public function upload($filename) {
		$upload = new \Think\Upload (); // 实例化上传类
		$upload->maxSize = 3145728; // 设置附件上传大小
		$upload->exts = array ('jpg', 'gif', 'png', 'jpeg' ); // 设置附件上传类型
		$upload->rootPath = './Public/Upload/'; // 设置附件上传根目录
		$upload->savePath = '';
		// 上传单个文件 
		$info = $upload->uploadOne ( $filename );
		if (! $info) { // 上传错误提示错误信息
			$this->error ( $upload->getError () );
			exit ();
		} else { // 上传成功 获取上传文件信息
			return $info ['savepath'] . $info ['savename'];
		}
	}

}
?>